﻿using System;
using System.Linq;
using Attendences.Server.Model;
using System.Collections.Generic;
using Attendences.Server.Common;
using System.Xml;

namespace Attendences.Server.Biz
{
    public class SynBiz
    {
        private enum DutyType
        {
            行政值班白天 = 100,
            行政值班晚上 = 200,
            大厅值班 = 300,
            节假日上午 = 400,
            节假日下午 = 500,
            戬浜值班 = 600,


        }
        UserDCDataContext wsafDc = new UserDCDataContext();
        msgService.MessagesService service = new Attendences.Server.msgService.MessagesService();
        public SynBiz()
        {
            //os = new Attendences.Server.wsafServer.OrganizationService();
            // service = new Attendences.Server.msgService.MessagesService();
        }
        //private UserDCDataContext userDc = new UserDCDataContext();


        private string GetReceiver(ViewAttendForAlert vtf, Attendences.Server.Model.AttendenceDCDataContext dc)
        {
            string receivers = "<Receivers><Receiver><Name>{0}</Name><DisplayName>{1}</DisplayName><NodeType>User</NodeType><Email></Email><LCS></LCS><Mobile>{2}</Mobile><Fax></Fax></Receiver></Receivers>";
            if (vtf.UserType.ToLower() == "other")
            {
                OtherUser ou = dc.OtherUsers.FirstOrDefault(l => l.ID == vtf.UserID);
                if (ou != null)
                {

                    receivers = string.Format(receivers, ou.Name, ou.DisplayName, ou.Mobile);
                }
                else
                {
                    receivers = string.Format(receivers, "", "", "");
                }

            }
            else
            {
                #region 2012-4-26


                //string userInfo = os.GetUserInfoByID(string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><value type=""System.Guid"">{0}</value>", vtf.UserID));

                //XmlDocument doc = new XmlDocument();
                //try
                //{
                //    doc.LoadXml(userInfo);
                //    string userName = string.Empty;
                //    string displayName = string.Empty;
                //    string phone = string.Empty;

                //    XmlNode xn = doc.SelectSingleNode("//entity/properties/property[@name='Name']");
                //    if (xn != null)
                //        userInfo = xn.InnerText;
                //    xn = doc.SelectSingleNode("//entity/properties/property[@name='DisplayName']");
                //    if (xn != null)
                //        displayName = xn.InnerText;
                //    xn = doc.SelectSingleNode("//entity/extend/property[@name='Mobile']");
                //    if (xn != null)
                //        phone = xn.InnerText;

                //    receivers = string.Format(receivers, userName, displayName, phone);
                //}
                //catch (Exception ee)
                //{
                //    LogHelper.WriteLog(ee.Message);
                //}

                #endregion

                #region MyRegion

                UserView ur = wsafDc.UserViews.SingleOrDefault(l => l.ID == vtf.UserID);
                if (ur != null)
                {
                    string phone = string.Empty;

                    PropertyData pd = wsafDc.PropertyDatas.SingleOrDefault(l => l.NodeID == vtf.UserID && l.PropertyID == new Guid(Config.PhonePropertyID));
                    if (pd != null)
                        phone = pd.ValueString;

                    receivers = string.Format(receivers, ur.Name, ur.DisplayName, phone);
                }
                else
                {
                    receivers = string.Format(receivers, "", "", "");
                }


                #endregion


            }
            return receivers;
        }

        private string ModuleString(string moduleid)
        {
            return string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><value type=""System.Guid"">{0}</value>", moduleid);
        }
        private string SendTimeString()
        {
            return string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><value type=""System.DateTime"">{0}</value>", DateTime.Today.AddHours(7).AddMinutes(30));
        }
        private Guid GetMessageID(string content)
        {
            Guid gd = Guid.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(content);
                gd = new Guid(doc.DocumentElement.InnerText);
            }
            catch

            { }

            return gd;


        }

        public void SynUser()
        {

            string title = "{0}提醒：{1}到{2}";
            Attendences.Server.Model.AttendenceDCDataContext dc = new Attendences.Server.Model.AttendenceDCDataContext();
            DateTime dt = DateTime.Today;

            List<AttendentSmsRecord> sentList = new List<AttendentSmsRecord>();

            if (DateTime.Now.AddMinutes(4) > dt.AddHours(7).AddMinutes(30) && DateTime.Now < dt.AddHours(7).AddMinutes(30))
            {
                #region 行政值班白天
                List<ViewAttendForAlert> list2 = dc.ViewAttendForAlerts.Where(l => l.AttendTimeStart >= dt.AddDays(1) && l.AttendTimeStart <= dt.AddDays(2).AddSeconds(-1) && l.AttendTimeEnd >= dt.AddDays(1) && l.AttendTimeEnd <= dt.AddDays(2).AddSeconds(-1) && l.Remark == ((int)DutyType.行政值班白天).ToString()).ToList();
                LogHelper.WriteLog(DateTime.Now.ToString() + "行政值班白天 " + list2.Count.ToString());
                foreach (ViewAttendForAlert item in list2)
                {
                    AttendentSmsRecord hasSent = dc.AttendentSmsRecords.FirstOrDefault(l => l.AttendenceItemID == item.ID);

                    if (hasSent == null)
                    {
                        string content = string.Format(title, "行政值班(白天)", item.AttendTimeStart.Value.ToString("yyyy年MM月dd日HH点mmm分"), item.AttendTimeEnd.Value.ToString("yyyy年MM月dd日HH点mmm分"));
                        string msg = service.SendMessageByModuleID(ModuleString(Config.DaTingModuleID), "admin", GetReceiver(item, dc), content, content, false, 0, "", SendTimeString());
                        Guid id = GetMessageID(msg);
                        LogHelper.WriteLog(DateTime.Now.ToString() + "行政值班白天 " + id);
                        if (id != Guid.Empty)
                        {
                            AttendentSmsRecord atr = new AttendentSmsRecord();
                            atr.AttendenceItemID = item.ID;
                            if (!sentList.Contains(atr, new RecodeComparer()))
                                sentList.Add(atr);

                        }
                    }
                }


                #endregion
                #region 行政值班晚上

                List<ViewAttendForAlert> list3 = dc.ViewAttendForAlerts.Where(l => l.AttendTimeStart >= dt && l.AttendTimeStart <= dt.AddDays(1).AddSeconds(-1) && l.AttendTimeEnd >= dt && l.AttendTimeEnd <= dt.AddDays(1).AddHours(12).AddSeconds(-1) && l.Remark == ((int)DutyType.行政值班晚上).ToString()).ToList();
                LogHelper.WriteLog(DateTime.Now.ToString() + "行政值班晚上 " + list3.Count.ToString());
                foreach (ViewAttendForAlert item in list3)
                {
                    AttendentSmsRecord hasSent = dc.AttendentSmsRecords.FirstOrDefault(l => l.AttendenceItemID == item.ID);

                    if (hasSent == null)
                    {
                        string content = string.Format(title, "行政值班(晚上)", item.AttendTimeStart.Value.ToString("yyyy年MM月dd日HH点mmm分"), item.AttendTimeEnd.Value.ToString("yyyy年MM月dd日HH点mmm分"));
                        string msg = service.SendMessageByModuleID(ModuleString(Config.DaTingModuleID), "admin", GetReceiver(item, dc), content, content, false, 0, "", SendTimeString());
                        Guid id = GetMessageID(msg);
                        LogHelper.WriteLog(DateTime.Now.ToString() + "行政值班晚上 " + id);
                        if (id != Guid.Empty)
                        {
                            AttendentSmsRecord atr = new AttendentSmsRecord();
                            atr.AttendenceItemID = item.ID;
                            if (!sentList.Contains(atr, new RecodeComparer()))
                                sentList.Add(atr);

                        }
                    }
                }


                #endregion
               

                #region 节假日上午

                List<ViewAttendForAlert> list5 = dc.ViewAttendForAlerts.Where(l => l.AttendTimeStart >= dt.AddDays(1) && l.AttendTimeStart <= dt.AddDays(2).AddSeconds(-1) && l.AttendTimeEnd >= dt.AddDays(1) && l.AttendTimeEnd <= dt.AddDays(2).AddSeconds(-1) && l.Remark == ((int)DutyType.节假日上午).ToString()).ToList();
                LogHelper.WriteLog(DateTime.Now.ToString() + "节假日上午 " + list5.Count.ToString());
                foreach (ViewAttendForAlert item in list5)
                {
                    AttendentSmsRecord hasSent = dc.AttendentSmsRecords.FirstOrDefault(l => l.AttendenceItemID == item.ID);

                    if (hasSent == null)
                    {
                        string content = string.Format(title, "节假日上午值班", item.AttendTimeStart.Value.ToString("yyyy年MM月dd日HH点mi分"), item.AttendTimeEnd.Value.ToString("yyyy年MM月dd日HH点mi分"));
                        string msg = service.SendMessageByModuleID(ModuleString(Config.DaTingModuleID), "admin", GetReceiver(item, dc), content, content, false, 0, "", SendTimeString());
                        Guid id = GetMessageID(msg);
                        LogHelper.WriteLog(DateTime.Now.ToString() + "节假日上午 " + id);
                        if (id != Guid.Empty)
                        {
                            AttendentSmsRecord atr = new AttendentSmsRecord();
                            atr.AttendenceItemID = item.ID;
                            if (!sentList.Contains(atr, new RecodeComparer()))
                                sentList.Add(atr);

                        }
                    }
                }


                #endregion

                #region 节假日下午

                List<ViewAttendForAlert> list6 = dc.ViewAttendForAlerts.Where(l => l.AttendTimeStart >= dt.AddDays(1) && l.AttendTimeStart <= dt.AddDays(2).AddSeconds(-1) && l.AttendTimeEnd >= dt.AddDays(1) && l.AttendTimeEnd <= dt.AddDays(2).AddSeconds(-1) && l.Remark == ((int)DutyType.节假日下午).ToString()).ToList();
                LogHelper.WriteLog(DateTime.Now.ToString() + "节假日下午 " + list6.Count.ToString());
                foreach (ViewAttendForAlert item in list6)
                {
                    AttendentSmsRecord hasSent = dc.AttendentSmsRecords.FirstOrDefault(l => l.AttendenceItemID == item.ID);

                    if (hasSent == null)
                    {
                        string content = string.Format(title, "节假日下午值班", item.AttendTimeStart.Value.ToString("yyyy年MM月dd日HH点mi分"), item.AttendTimeEnd.Value.ToString("yyyy年MM月dd日HH点mi分"));
                        string msg = service.SendMessageByModuleID(ModuleString(Config.DaTingModuleID), "admin", GetReceiver(item, dc), content, content, false, 0, "", SendTimeString());
                        Guid id = GetMessageID(msg);
                        LogHelper.WriteLog(DateTime.Now.ToString() + "节假日下午 " + id);
                        if (id != Guid.Empty)
                        {
                            AttendentSmsRecord atr = new AttendentSmsRecord();
                            atr.AttendenceItemID = item.ID;
                            if (!sentList.Contains(atr, new RecodeComparer()))
                                sentList.Add(atr);

                        }
                    }
                }


                #endregion

                #region 戬浜

                List<ViewAttendForAlert> list = dc.ViewAttendForAlerts.Where(l => l.AttendTimeStart >= dt.AddDays(1) && l.AttendTimeStart <= dt.AddDays(2).AddSeconds(-1) && l.AttendTimeEnd >= dt.AddDays(1) && l.AttendTimeEnd <= dt.AddDays(2).AddSeconds(-1) && l.Remark == ((int)DutyType.戬浜值班).ToString()).ToList();

                foreach (ViewAttendForAlert item in list)
                {
                    AttendentSmsRecord hasSent = dc.AttendentSmsRecords.FirstOrDefault(l => l.AttendenceItemID == item.ID);

                    if (hasSent == null)
                    {
                        string content = string.Format(title, "戬浜值班", item.AttendTimeStart.Value.ToString("yyyy年MM月dd日HH点mi分"), item.AttendTimeEnd.Value.ToString("yyyy年MM月dd日HH点mi分"));
                        string msg = service.SendMessageByModuleID(ModuleString(Config.DaTingModuleID), "admin", GetReceiver(item, dc), content, content, false, 0, "", SendTimeString());
                        Guid id = GetMessageID(msg);

                        if (id != Guid.Empty)
                        {
                            AttendentSmsRecord atr = new AttendentSmsRecord();
                            atr.AttendenceItemID = item.ID;
                            if (!sentList.Contains(atr, new RecodeComparer()))
                                sentList.Add(atr);

                        }
                    }
                }
                #endregion
            }
            if (DateTime.Now.AddMinutes(4) > dt.AddHours(16) && DateTime.Now < dt.AddHours(16))
            {
                #region 大厅值班

                List<ViewAttendForAlert> list4 = dc.ViewAttendForAlerts.Where(l => l.AttendTimeStart >= dt && l.AttendTimeStart <= dt.AddDays(1).AddSeconds(-1) && l.AttendTimeEnd >= dt && l.AttendTimeEnd <= dt.AddDays(1).AddSeconds(-1) && l.Remark == ((int)DutyType.大厅值班).ToString()).ToList();
                LogHelper.WriteLog(DateTime.Now.ToString() + "大厅值班 " + list4.Count.ToString());
                foreach (ViewAttendForAlert item in list4)
                {
                    AttendentSmsRecord hasSent = dc.AttendentSmsRecords.FirstOrDefault(l => l.AttendenceItemID == item.ID);

                    if (hasSent == null)
                    {
                        string content = string.Format(title, "大厅值班", item.AttendTimeStart.Value.ToString("yyyy年MM月dd日HH点mmm分"), item.AttendTimeEnd.Value.ToString("yyyy年MM月dd日HH点mmm分"));
                        string msg = service.SendMessageByModuleID(ModuleString(Config.DaTingModuleID), "admin", GetReceiver(item, dc), content, content, false, 0, "", SendTimeString());
                        Guid id = GetMessageID(msg);
                        LogHelper.WriteLog(DateTime.Now.ToString() + "大厅值班 " + id);
                        if (id != Guid.Empty)
                        {
                            AttendentSmsRecord atr = new AttendentSmsRecord();
                            atr.AttendenceItemID = item.ID;
                            if (!sentList.Contains(atr, new RecodeComparer()))
                                sentList.Add(atr);

                        }
                    }
                }


                #endregion

            }


            if (sentList.Count > 0)
            {
                dc.AttendentSmsRecords.InsertAllOnSubmit(sentList);
                dc.SubmitChanges();

            }
        }

        ~SynBiz()
        {
            //os.Dispose();

        }
    }
}